package com.bizframework.core.serialization.xstream.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.thoughtworks.xstream.converters.SingleValueConverter;

public class DateConverter implements SingleValueConverter {

	public DateConverter() {
		super();
	}

	public boolean canConvert(@SuppressWarnings("rawtypes") Class clazz) {
		return Date.class.isAssignableFrom(clazz);
	}

	public Object fromString(String value) {
		if (value == null) {
			return null;
		}
		try {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) value);

		} catch (ParseException e) {
			try {
				return new SimpleDateFormat("yyyyMMdd").parse((String) value);
			} catch (ParseException e1) {
				try {
					return new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse((String) value);
				} catch (ParseException e2) {
					throw new RuntimeException("invalid date " + value);
				}
			}
		}
	}

	public String toString(Object obj) {
		Date date = (Date) obj;
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

}